package com.rockcent.api.utils;

import android.os.AsyncTask;

import com.rockcent.action.CallbackListener;
import com.rockcent.api.ApiResponse;

/**
 * @author 李纪钢 keegan704@qq.com
 * @version 1.0 创建时间：14/11/12
 */
public abstract class NetworkTask<T> extends AsyncTask<Void, Void, Void> {

    private CallbackListener<T> callbackListener;
    private ApiResponse<T> response;
    private boolean isCancel = false;

    public NetworkTask(CallbackListener<T> callbackListener) {
        this.callbackListener = callbackListener;
    }

    public void cancel() {
        isCancel = true;
        super.cancel(true);
    }

    @Override
    protected Void doInBackground(Void... params) {
        response = run();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (callbackListener == null || response == null) {
            return;
        }
        callbackListener.onFinish();
        if (!isCancel) {
            if (response.isSuccess()) {
                T data = response.getObj();
                if (data == null) {
                    data = response.getObjList();
                }
                callbackListener.onSuccess(data);
            } else {
                callbackListener.onFailure(response.getEvent(), response.getMsg());
            }
        }
    }

    public abstract ApiResponse<T> run();
}
